package com.zzyy.study;

import lombok.SneakyThrows;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @auther zzyy
 * @create 2024-05-26 10:50
 */
public class ReflectDemo
{
    public static final int _1Y = 100000000;

    public static void m1_newObject()
    {
        Fish fish = new Fish();
    }

    //=============V1
    public static void m2_newObjectWithReflect()
    {
        try
        {
            Fish fish = Fish.class.getDeclaredConstructor().newInstance();

            /*Constructor<?> constructor = Class.forName("com.zzyy.study.Fish").getDeclaredConstructor();
            Fish o = (Fish) constructor.newInstance();*/
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }


    //=============V2
    private static Constructor<Fish> fishConstructor;
    static
    {
        try
        {
            fishConstructor = Fish.class.getDeclaredConstructor();
            fishConstructor.setAccessible(true);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
    public static void m2_newObjectWithReflectV2()
    {
        try
        {
            Fish fish = fishConstructor.newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    public static void main(String[] args)
    {
        long startTime = System.currentTimeMillis();
        for (int i = 1; i <= 5 * _1Y ; i++)
        {
            //m1_newObject();//2 毫秒
            //m2_newObjectWithReflect(); //14137 毫秒
            m2_newObjectWithReflectV2();//488 毫秒
        }
        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: "+(endTime - startTime) +" 毫秒");
    }
}


class Fish
{
    private int id;
    private String fishName;

    public Fish() {}

    public Fish(int id, String fishName)
    {
        this.id = id;
        this.fishName = fishName;
        System.out.println("----come in");
    }

    public int jump(int i)
    {
        System.out.println("鱼跃龙门");
        return i;
    }
}